package cuong.ptit.androidvn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.jar.Attributes.Name;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import cuong.ptit.andoridvn.R;
import cuong.ptit.androidvn.helper.Function;
import cuong.ptit.androidvn.helper.JSONParser;
import cuong.ptit.androidvn.widget.PullAndLoadListView;
import cuong.ptit.androidvn.widget.PullAndLoadListView.OnLoadMoreListener;
import cuong.ptit.androidvn.widget.PullToRefreshListView.OnRefreshListener;

/*
 * @author LeCuong 
 * @version 1.0
 */

public class GetPostUser extends ListActivity {

	private ProgressDialog pDialog;
	private String user_name, user_id, hash_user, all_post;
	private int loadCount = 10;
	private int in = 0;

	private ArrayList<HashMap<String, String>> list_idthread;
	private ArrayList<HashMap<String, String>> list_id;

	// json post
	private JSONParser jsonParser = new JSONParser();
	private ArrayList<HashMap<String, String>> listPost;
	private ArrayList<HashMap<String, String>> listPostLoad;
	private static final String url_post = "http://android.vn/api.php?action=getPosts&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&order_by=post_date";
	private static final String TAG_MESS = "message";
	private static final String TAG_DATE = "post_date";
	private static final String TAG_ID_THREAD = "thread_id";
	private static final String TAG_USER = "username";
	private static final String TAG_TITLE = "title";
	private static final String TAG_NODE_ID = "node_id";

	// json all post user
	private final static String url_user = "http://android.vn/api.php?action=getUser";
	private final static String TAG_MESSAGE = "message_count";

	// json title thread user
	private ArrayList<HashMap<String, String>> listTitleThread = new ArrayList<HashMap<String, String>>();
	private static final String url_thread = "http://android.vn/api.php?action=getThread&hash=greenforest:4adac471b51a35dc2c7fcd4229a6370856fca49a831e92858476af93f4636711";
	private static final String TAG_THR = "title";
	private static final String TAG_ID_THR = "thread_id";
	private static final String TAG_ID_NODE = "node_id";

	// json forum
	private ArrayList<HashMap<String, String>> listBox;
	private static final String url_box = "http://android.vn/api.php?action=getNodes&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&node_type=forum";
	private static final String TAG_BOX = "title";
	private static final String TAG_ID_BOX = "node_id";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.get_post_user_activty);

		// get intent user_name, user_id
		Intent i = getIntent();
		user_name = i.getStringExtra("user_name");
		user_id = i.getStringExtra("user_idname");
		String has = i.getStringExtra("user_hash");
		hash_user = user_name + ":" + has;

		// Load content
		new LoadPostUser().execute();

		((PullAndLoadListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {

					@Override
					public void onRefresh() {
						new RefreshPostUser().execute();

					}
				});

		((PullAndLoadListView) getListView())
				.setOnLoadMoreListener(new OnLoadMoreListener() {

					@Override
					public void onLoadMore() {

						loadCount = loadCount + 10;
						in = listPost.size();
						new LoadMorePostUser().execute();

					}
				});

	}

	// refresh post user-----------------------------------------------
	class RefreshPostUser extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... args) {
			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}

			// load json limit new
			listPost.clear();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("author", user_id));

			String jsonnew = jsonParser
					.makeHttpRequest(url_post, "GET", params);

			try {

				JSONObject posts = new JSONObject(jsonnew);
				JSONObject post = posts.getJSONObject("posts");

				Iterator<?> keys = post.keys();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					JSONObject c = post.getJSONObject(key);

					String id_thread = c.getString(TAG_ID_THREAD);
					String date = c.getString(TAG_DATE);
					String messages = c.getString(TAG_MESS);

					// get 20 word frist
					String message2 = Function.getFrist10Word(messages)
							+ "....";

					String user = c.getString(TAG_USER);
					// get name title thread
					String titleThread = Function.GetNameThread(
							listTitleThread, id_thread, "title");

					// get name box
					String node_id = Function.GetNameThread(listTitleThread,
							id_thread, "node_id");
					String node_title = Function.GetNameBox(listBox, node_id);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THREAD, id_thread);
					map.put(TAG_DATE, date);
					map.put(TAG_MESS, message2);
					map.put(TAG_USER, user);
					map.put(TAG_THR, titleThread);
					map.put(TAG_NODE_ID, node_title);

					listPost.add(map);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			//Function.CollectionSortBA(listPost, "post_date");
			loadCount = 10;
			in = 0;

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onCancelled();
		}

	}

	// load more post user---------------------------------------------
	class LoadMorePostUser extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... agrs) {

			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}

			// load json limit new
			listPostLoad = new ArrayList<HashMap<String, String>>();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("author", user_id));
			params.add(new BasicNameValuePair("limit", String
					.valueOf(loadCount)));

			String jsonload = jsonParser.makeHttpRequest(url_post, "GET",
					params);

			try {

				JSONObject posts = new JSONObject(jsonload);
				JSONObject post = posts.getJSONObject("posts");

				Iterator<?> keys = post.keys();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					JSONObject c = post.getJSONObject(key);

					String id_thread = c.getString(TAG_ID_THREAD);
					String date = c.getString(TAG_DATE);
					String messages = c.getString(TAG_MESS);

					// get 20 word frist
					String message2 = Function.getFrist10Word(messages)
							+ "....";
					String user = c.getString(TAG_USER);

					// get name title thread
					String titleThread = Function.GetNameThread(
							listTitleThread, id_thread, TAG_TITLE);

					// get name box
					String node_id = Function.GetNameThread(listTitleThread,
							id_thread, TAG_NODE_ID);
					String node_title = Function.GetNameBox(listBox, node_id);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THREAD, id_thread);
					map.put(TAG_DATE, date);
					map.put(TAG_MESS, message2);
					map.put(TAG_USER, user);
					map.put(TAG_TITLE, titleThread);
					map.put(TAG_NODE_ID, node_title);

					listPostLoad.add(map);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			/* Function.CollectionSortBA(listPostLoad, "post_date"); */

			// check load

			if (listPost.size() < listPostLoad.size()) {
				// add item new
				for (int a = in; a < listPostLoad.size(); a++) {
					HashMap<String, String> map = listPostLoad.get(a);
					listPost.add(map);
				}
			}

			/* Function.CollectionSortBA(listPost, "post_date"); */

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
			super.onCancelled();
		}
	}

	// load post user--------------------------------------------
	class LoadPostUser extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(GetPostUser.this);
			pDialog.setMessage("Loading....");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... args) {

			// title box
			listBox = new ArrayList<HashMap<String, String>>();

			// id thread no reapeat
			list_idthread = new ArrayList<HashMap<String, String>>();

			// id thread reapeat
			list_id = new ArrayList<HashMap<String, String>>();

			// get 10 post frist
			listPost = new ArrayList<HashMap<String, String>>();

			// get all title box------------------------
			List<NameValuePair> pa = new ArrayList<NameValuePair>();
			String jsonForum = jsonParser.makeHttpRequest(url_box, "GET", pa);

			// get all post comment user----------
			List<NameValuePair> paramsPost = new ArrayList<NameValuePair>();
			paramsPost.add(new BasicNameValuePair("hash", hash_user));
			String json_user = jsonParser.makeHttpRequest(url_user, "GET",
					paramsPost);

			// load json post user: default=10---------
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("author", user_id));
			String jsonPost = jsonParser.makeHttpRequest(url_post, "GET",
					params);

			// get all title forum---------------------
			try {

				JSONObject forums = new JSONObject(jsonForum);
				JSONObject forum = forums.getJSONObject("nodes");

				Iterator<?> keysf = forum.keys();

				while (keysf.hasNext()) {
					String key = (String) keysf.next();
					JSONObject c = forum.getJSONObject(key);

					String id_node = c.getString(TAG_ID_BOX);
					String title_node = c.getString(TAG_BOX);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_BOX, id_node);
					map.put(TAG_BOX, title_node);

					listBox.add(map);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			// get all post=56-----------------------
			try {

				JSONObject p = new JSONObject(json_user);
				if (p != null) {
					all_post = p.getString(TAG_MESSAGE);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			// load json all post id thread-----------------------
			try {
				List<NameValuePair> paramsall = new ArrayList<NameValuePair>();
				paramsall.add(new BasicNameValuePair("author", user_id));
				paramsall.add(new BasicNameValuePair("limit", all_post));
				String json_all = jsonParser.makeHttpRequest(url_post, "GET",
						paramsall);

				JSONObject posts_all = new JSONObject(json_all);
				JSONObject postall = posts_all.getJSONObject("posts");

				Iterator<?> keys_all = postall.keys();

				while (keys_all.hasNext()) {
					String key = (String) keys_all.next();

					JSONObject c = postall.getJSONObject(key);
					String id_thread = c.getString(TAG_ID_THREAD);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THREAD, id_thread);

					list_id.add(map);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			Function.RemoreItemRepeatArray(list_id);

			// load title to thread id
			// get title_thread to id_thread-------------------------------
			String value = "";
			for (int i = 0; i < list_id.size(); i++) {
				HashMap<String, String> map = list_id.get(i);
				value = map.get("thread_id");

				List<NameValuePair> params_title = new ArrayList<NameValuePair>();
				params_title.add(new BasicNameValuePair("value", value));

				String jsontitle = jsonParser.makeHttpRequest(url_thread,
						"GET", params_title);

				try {
					JSONObject a = new JSONObject(jsontitle);
					if (a != null) {
						String id_thread = a.getString("thread_id");
						String title = a.getString("title");
						String id_node = a.getString("node_id");

						HashMap<String, String> mapp = new HashMap<String, String>();
						mapp.put("thread_id", id_thread);
						mapp.put("title", title);
						mapp.put("node_id", id_node);
						listTitleThread.add(mapp);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			// load json post 10 --------------------------
			try {

				JSONObject posts = new JSONObject(jsonPost);
				JSONObject post = posts.getJSONObject("posts");

				Iterator<?> keys = post.keys();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					JSONObject c = post.getJSONObject(key);

					String id_thread = c.getString(TAG_ID_THREAD);
					String date = c.getString(TAG_DATE);
					String messages = c.getString(TAG_MESS);

					// get 20 word frist
					String message2 = Function.getFrist10Word(messages)
							+ "....";
					String user = c.getString(TAG_USER);

					// get name title thread
					String titleThread = Function.GetNameThread(
							listTitleThread, id_thread, "title");

					// get name box
					String node_id = Function.GetNameThread(listTitleThread,
							id_thread, "node_id");
					String node_title = Function.GetNameBox(listBox, node_id);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THREAD, id_thread);
					map.put(TAG_DATE, date);
					map.put(TAG_MESS, message2);
					map.put(TAG_USER, user);
					map.put(TAG_TITLE, titleThread);
					map.put(TAG_NODE_ID, node_title);

					listPost.add(map);

					Log.d("title", "id=" + id_thread + "=" + node_title + "=="
							+ titleThread);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			// remove item repeat array list_id

			/*
			 * Function.CollectionSort(list_id, "thread_id");
			 * Function.CollectionSortBA(listPost, "post_date");
			 */
			Log.d("listThread", ">" + listPost + ">" + listTitleThread);

			Log.d("list id", ">" + list_id + "zG=" + list_id.size() + "zN="
					+ listPost.size());

			Log.d("id no reapeat", ">" + list_idthread + "size="
					+ list_idthread.size());

			Log.d("list title", ">" + listTitleThread);
			Log.d("list title forum", ">" + listBox);

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			pDialog.dismiss();

			runOnUiThread(new Runnable() {
				public void run() {
					ListAdapter adapter = new SimpleAdapter(GetPostUser.this,
							listPost, R.layout.list_item_get_post_user,
							new String[] { TAG_MESS, TAG_DATE, TAG_USER,
									TAG_BOX, TAG_TITLE, TAG_NODE_ID },
							new int[] { R.id.tv_title_getMessPostdUser,
									R.id.tv_date_getPostUser,
									R.id.tv_user_getPostUser,
									R.id.tv_title_getPostUser,
									R.id.tv_title_getPostUser,
									R.id.tv_box_getPostUser });

					setListAdapter(adapter);
				}
			});
			super.onPostExecute(result);
		}
	}

}
